/*
 * iframeTab
 * Version: 1.0.0
 *
 * Plugin that can simulate browser to open links as tab and iframe in a page
 *
 * https://github.com/HenriettaSu/iframeTab
 *
 * License: MIT
 *
 * Released on: July 7, 2016
*/

(function () {
    iframeTab = jQuery.prototype = {
		iframeHeight: function(h) {
            var ifm = $(".tab-panel.active iframe")[0];
            var subWeb = $(document).frames ? $(document).frames["iframepage"].document : ifm.contentDocument;
            if(ifm != null && subWeb != null && subWeb.body) { 
            	if(h){
            		ifm.height =parseFloat(ifm.height)+h;
            	}else{
            		if(subWeb.body.scrollHeight){
            			ifm.height = subWeb.body.scrollHeight;
            		}else{
            			ifm.height = subWeb.body.clientHeight;
            		}
            	}
            }
        },
        childResize:function(){
        	var h = document.body.scrollHeight;
        	var content_iframe = $($(".tab-panel.active iframe",window.parent.document)[0]);//获取iframeID
        	content_iframe.attr("height",h);
        	return content_iframe.length>0;
        },
        iframeResize: function() {
            var ifm = $(".tab-panel.active iframe")[0];
            var subWeb = $(document).frames ? $(document).frames["iframepage"].document : ifm.contentDocument;
            if(ifm != null && subWeb != null && subWeb.body) { 
            	if(subWeb.body && subWeb.body.scrollHeight){
            		ifm.height = subWeb.body.scrollHeight;
            	}else{
            		ifm.height = subWeb.body.clientHeight;
            	}
				
				if(document.body.scrollWidth<subWeb.body.scrollWidth+100){  
					  $(ifm).attr("scrolling","yes"); 
					  $(subWeb.body).css("width",subWeb.body.scrollWidth+"px") 
				}else{ 

	                var scroll = $(ifm).attr('data-scroll');
	                if(scroll=="no"){
	                	$(ifm).attr("scrolling","no");
	                	$(subWeb.body).css("width","100%") 
	                } 
				} 
				ifm.width = subWeb.body.scrollWidth;
            }
        },
		 iframeWidth: function() {
            var ifm = $(".tab-panel.active iframe")[0];
            var subWeb = $(document).frames ? $(document).frames["iframepage"].document : ifm.contentDocument;
            if(ifm != null && subWeb != null && subWeb.body) { 
                if(subWeb.body.scrollWidth){
            		ifm.width = subWeb.body.scrollWidth;
            	}else{
            		ifm.width = subWeb.body.clientWidth;
            	}
				if(document.body.scrollWidth<subWeb.body.scrollWidth){  
					  $(ifm).attr("scrolling","yes");
				}else{ 
					var scroll = $(ifm).attr('data-scroll');
	                if(scroll=="no"){
	                	$(ifm).attr("scrolling","no");
	                } 
				} 
            }
        },
        //option = {href:"",name:"",mul:"",reload:"",scroll:""}
		 open: function(option) {
			 var $this = this;
             var p = window.parent.document,
             options = $this.options,
             tabUl = options.tabUl,
             tabLi = options.tabLi,
             tabBody = options.tabBody,
             tabPan = options.tabPan,
             closesBtnClass = options.closesBtnClass,
             newTabPan = options.newTabPan,
             tabCloseBtn = '[data-btn="close"]',
             closeBtn = tabLi + tabCloseBtn;
			 
			 var option = option||{};
			 var link = option.href,
             name = option.name,
             mul = option.mul,
             reload = option.reload,
             $tabUl = $(tabUl, p),
             $tabLi = $(tabLi, p),
             $tabBody = $(tabBody, p),
             $tabPan = $(tabPan, p),
             tab = $tabUl.find('[data-name="' + name + '"]').data('tab');
         if(link=="" || link=="#" || link=="javascript:void(0)"){
         	link = option.url;
         }
         var scroll = option.scroll;
         if(scroll=="" || scroll==undefined){
         	scroll = "no";
         } 
         var iframe = $('<iframe src="' + link + '" data-iframe="' + link + '" data-num="' + $this.tnum + '" marginheight="0" marginwidth="0" frameborder="0" " data-scroll="' + scroll + '"  scrolling="'+scroll+'" onload="iframeTab.iframeHeight()"></iframe>');
         // 插入新標籤
         function stellen() {
             $tabLi.removeClass('active').addClass('noactive');
             $tabUl.append('<li role="presentation" class="active nav nav-pills img-polaroid" data-tab="' + link + '" data-name="' + name + '" data-num="' + $this.tnum + '">' + name + '<i class="tab_close ' + closesBtnClass + '" data-btn="close"></i></li>');
             $tabPan.removeClass('active').addClass('noactive');
             $tabBody.append(iframe);
             iframe.wrap(newTabPan);
             $this.tnum = $this.tnum + 1;
         }
         if ($(tabUl + ' [data-name="' + name + '"]', p).length > 0 && typeof mul === 'undefined') {
             if (!$(tabUl + ' [data-tab="' + link + '"]', p).length > 0) {
                 $tabUl.find('[data-name="' + name + '"]').remove();
                 $tabBody.find('iframe[data-iframe="' + tab + '"]').remove();
                 stellen();
             } else {
                 $tabLi.removeClass('active').addClass('noactive');
                 $tabUl.find('[data-tab="' + link + '"]').addClass('active').removeClass('noactive');
                 $tabPan.removeClass('active').addClass('noactive');
                 $tabBody.find('iframe[data-iframe="' + link + '"]').parents(tabPan).addClass('active').removeClass('noactive');
                 if (reload) {
                     $tabBody.find('iframe[data-iframe="' + link + '"]').attr('src', link);
                 }
             }
         } else {
             stellen();
         }
		 }
        ,
        init: function (option) {
        	if(!iframeTab.inited){
        		iframeTab.inited = true;
        	}else{
        		return;
        	}
			 var $this = this;
        	var options = $this.options = $.extend({
                tabUl: '.tabs-header ul',
                tabLi: '.tabs-header li',
                tabBody: '.tabs-body',
                tabPan: '.tab-panel',
                closesBtnClass: 'fa fa-close1',
                newTabPan: '<div class="tab-panel active"><div class="right_col" role="main"></div></div>'
            }, option);
        	var tnum = $this.tnum = 0;
        	var  
                p = window.parent.document,
               
                tabUl = options.tabUl,
                tabLi = options.tabLi,
                tabBody = options.tabBody,
                tabPan = options.tabPan,
                closesBtnClass = options.closesBtnClass,
                newTabPan = options.newTabPan,
                tabCloseBtn = '[data-btn="close"]',
                closeBtn = tabLi + tabCloseBtn;

            $(document).on('mouseup touchend', 'a[data-num]', function () { // 任意位置的超鏈接
            	var $this = $(this),
                    link = $this.attr('href'),
                    name = $this.attr('data-name') ? $this.data('name') : $this.text(),
                    mul = $this.data('mul'),
                    reload = $this.data('reload'),
                    $tabUl = $(tabUl, p),
                    $tabLi = $(tabLi, p),
                    $tabBody = $(tabBody, p),
                    $tabPan = $(tabPan, p),
                    tab = $tabUl.find('[data-name="' + name + '"]').data('tab');
                if(link=="" || link=="#" || link=="javascript:void(0)"){
                	link = $this.attr('url');
                }
                var scroll = $this.attr('data-scroll');
                if(scroll=="" || scroll==undefined){
                	scroll = "no";
                } 
                var iframe = $('<iframe class="embed-responsive-item" src="' + link + '" data-iframe="' + link + '" data-num="' + tnum + '" marginheight="0" marginwidth="0" frameborder="0" " data-scroll="' + scroll + '"  scrolling="'+scroll+'" onload="iframeTab.iframeHeight()"></iframe>');
                $this.on('click', function (e) {
                    e.preventDefault();
                    e.stopPropagation();
                });
                //$('#sidebar-menu li ul').slideUp();
                var $li = $this.closest("li");
                clickItem($li);
                // 插入新標籤
                function stellen() {
                    $tabLi.removeClass('active').addClass('noactive');
                    $tabUl.append('<li role="presentation" class="active nav nav-pills img-polaroid" data-tab="' + link + '" data-name="' + name + '" data-num="' + tnum + '">' + name + '<i class="tab_close ' + closesBtnClass + '" data-btn="close"></i></li>');
                    $tabPan.removeClass('active').addClass('noactive');
                    $tabBody.append(iframe);
                    iframe.wrap(newTabPan);
                    tnum = tnum + 1;
                }
                var name = $.trim(name);
                if ($(tabUl + ' [data-name="' + name + '"]', p).length > 0 && typeof mul === 'undefined') {
                    if (!$(tabUl + ' [data-tab="' + link + '"]', p).length > 0) {
                        $tabUl.find('[data-name="' + name + '"]').remove();
                        $tabBody.find('iframe[data-iframe="' + tab + '"]').remove();
                        stellen();
                    } else {
                        $tabLi.removeClass('active').addClass('noactive');
                        $tabUl.find('[data-tab="' + link + '"]').addClass('active').removeClass('noactive');
                        $tabPan.removeClass('active').addClass('noactive');
                        $tabBody.find('iframe[data-iframe="' + link + '"]').parents(tabPan).addClass('active').removeClass('noactive');
                        if (reload) {
                            $tabBody.find('iframe[data-iframe="' + link + '"]').attr('src', link);
                        }
                    }
                } else {
                    stellen();
                }
            });
            $(document).on('click', tabLi, function () { // 標籤欄切換
                var $this = $(this),
                    link = $this.data('tab'),
                    cnum = $this.data('num'),
                    $tabUl = $(tabUl),
                    $tabLi = $(tabLi),
                    $tabBody = $(tabBody),
                    $tabPan = $(tabPan);
                $tabLi.removeClass('active').addClass('noactive');
                $tabUl.find('[data-tab="' + link + '"][data-num="' + cnum + '"]').addClass('active').removeClass('noactive');
                $tabPan.removeClass('active').addClass('noactive');
                $tabBody.find('iframe[data-iframe="' + link + '"][data-num="' + cnum + '"]').parents(tabPan).addClass('active').removeClass('noactive');
				iframeTab.iframeHeight();
                //$('#sidebar-menu li ul').slideUp();
				var as = $('#leftMenu').find("[url='"+link+"']");
				var $li = $(as[0]).closest("li");
				clickItem($li);
				return false;
            });
            $(document).on('click', tabCloseBtn, function (e) { // 刪除標籤
                var $this = $(this),
                    $li = $this.closest(tabLi),
                    tab = $li.data('tab'),
                    dnum = $li.data('num'),
                    $tabBody = $(tabBody),
                    $prev = $li.prev("li");
                var isActive = $li.hasClass("active");
                $li.remove();
                $tabBody.find('iframe[data-iframe="' + tab + '"][data-num="' + dnum + '"]').parents(tabPan).remove();
                if(isActive){
                	$prev.click();
                }
                e.stopPropagation();
            });
            $(document).on('mouseup touchend', '[data-source]', function () { // 點擊刷新tab
                var $this = $(this),
                    source = $this.data('source'),
                    $tabBody = $(tabBody, p);
                $tabBody.find('iframe[data-iframe="' + source + '"]').attr('src', source);
                iframeTab.iframeHeight();
            });
        }
    }
    
}());